<template>
  <div class="personCenterPage">
    <a-card title="个人信息" style="width: 100%; margin-bottom: 20px;">
      <div style="display: flex; align-items: center;">
        <a-avatar :size="100" :src="userInfo.userAvatar" style="margin-right: 20px;" />
        <div>
          <p>ID: {{ userInfo.id }}</p>
          <p>账号名: {{ userInfo.userAccount }}</p>
          <p>用户名:
            <span v-if="!isEditing">{{ userInfo.userName }}</span>
            <a-input v-else v-model:value="editUserName"  placeholder="请输入用户名" />
          </p>
          <p>角色: {{ userInfo.userRole }}</p>
          <p>创建时间:{{ dayjs(userInfo.createTime).format('YYYY-MM-DD HH:mm:ss') }}</p>
        </div>
      </div>
      <div style="text-align: right; margin-top: 20px;">
        <a-button v-if="!isEditing" type="primary" @click="startEdit">编辑</a-button>
        <a-button v-else type="primary" @click="saveEdit">保存</a-button>
      </div>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useLoginUserStore } from '@/stores/useLoginUserStore.js';
import dayjs from 'dayjs';
import { updateUserUsingPost } from '@/api/userController';
import { message } from 'ant-design-vue';

const isEditing = ref(false);
const editUserName = ref('');

const userInfo = ref({
  id: '',
  userAccount: '',
  userName: '',
  userAvatar: '',
  userRole: '',
  createTime: '',
  editTime: '',
});

const loginUserStore = useLoginUserStore();
userInfo.value = loginUserStore.loginUser;

function startEdit() {
  // 初始化编辑字段为当前用户名
  editUserName.value = userInfo.value.userName;
  isEditing.value = true;
}

async function saveEdit() {
  try {
    const response = await updateUserUsingPost({
      id: userInfo.value.id,
      userName: editUserName.value,
      // 如果有其他需要更新的字段，可以在这里添加
    });

    if (response.data) {
      // 更新本地状态
      userInfo.value.userName = editUserName.value;
      // 假设 loginUserStore.fetchLoginUser 是从后端获取最新用户信息的方法
      message.success("修改成功");
      isEditing.value = false;
    } else {
      console.error('修改失败', response.data);
      message.error('修改失败');
    }
  } catch (error) {
    console.error('保存错误', error);
    message.error('保存错误');
  }
}


</script>

<style scoped>
.personCenterPage {
  max-width: 700px;
  margin: 0 auto;
}

.personCenterPage p {
  margin: 5px 0;
}

.personCenterPage .a-input {
  width: 200px;
}
</style>
